package com.jagochan.mall.common.exception;

import com.jagochan.mall.common.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResult<?> handle(Throwable e) {
        log.error("系统异常：{}", e.getMessage(), e);
        return ApiResult.fail(400, "系统罢工了，请稍后再试");
    }

    @ExceptionHandler(BusinessException.class)
    public ApiResult<?> handle(BusinessException e) {
        log.info("业务异常：{}", e.getMessage(), e);
        return ApiResult.fail(400, e.getErrorMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<?> handle(MethodArgumentNotValidException e) {
        return ApiResult.fail(400, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

}
